package com.team.system.service.impl;

import com.team.common.core.exception.ServiceException;
import com.team.common.core.utils.StringUtils;
import com.team.system.api.domain.SysUser;
import com.team.system.domain.SysUserRole;
import com.team.system.mapper.SysUserMapper;
import com.team.system.mapper.SysUserRoleMapper;
import com.team.system.service.ISysUserRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserRegisterService implements ISysUserRegisterService {

    private static final Logger log = LoggerFactory.getLogger(SysUserRegisterService.class);
    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public Boolean registerUserByPhone(SysUser sysUser) {
        int insert = userMapper.insertUser(sysUser);
        if (insert > 0) {
            List<SysUserRole> userRoles = new ArrayList<>();
            if (StringUtils.isNotEmpty(sysUser.getRoleIds())) {
                for (Long roleId : sysUser.getRoleIds()) {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(sysUser.getUserId());
                    userRole.setRoleId(roleId);
                    userRoles.add(userRole);
                }
            }
            int i = userRoleMapper.batchUserRole(userRoles);
            if (i <= 0) {
                log.error("注册用户失败，用户ID: {}, 角色ID: {}", sysUser.getUserId(), sysUser.getRoleIds());
                throw new ServiceException("注册用户失败，角色关联失败");
            }
            log.info("注册用户成功，用户ID: {}, 角色ID: {}", sysUser.getUserId(), sysUser.getRoleIds());
            return true;
        }
        log.error("注册用户失败，用户信息: {}", sysUser);
        throw new ServiceException("注册用户失败，用户信息插入失败");
    }
}
